package client.comm.baoding.ui

import android.view.View
import androidx.lifecycle.lifecycleScope
import client.comm.commlib.comm_ui.draw.SpaceItemDecoration
import client.comm.commlib.widget.EmptyLayout
import client.comm.baoding.R
import client.comm.baoding.adapter.ZcjlAdapter
import client.comm.baoding.api.bean.Zcjl
import client.comm.baoding.databinding.ActivityWalletdetailBinding
import client.comm.baoding.ui.vm.WallteDetailViewModel
import client.comm.baoding.BaseMiddleActivity
import client.comm.commlib.network.data.PagingJsonResult
import kotlinx.coroutines.flow.collect

class WalletDetailActivity : BaseMiddleActivity<WallteDetailViewModel, ActivityWalletdetailBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_walletdetail
    }

    val adapter: ZcjlAdapter by lazy {
        ZcjlAdapter(this, mImgLoader).apply {
            refreshLoading = {
                if (itemCount == 0) {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
                }
            }
            refreshNotLoading = {
                binding.refreshLayout.isRefreshing = false

                if (itemCount == 0) {
                    binding.emptyLayout.errorType = EmptyLayout.NODATA
                } else {
                    binding.emptyLayout.visibility = View.GONE
                }
            }
            refreshError = {
                if (itemCount == 0)
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
            }
        }
    }

    override fun initView() {
        binding?.apply {
            event = this@WalletDetailActivity
            vm = viewModel
            recyclerView.adapter = adapter
            recyclerView.addItemDecoration(SpaceItemDecoration(10))
            emptyLayout.setOnClickListener { viewModel.holdOne() }
            refreshLayout.setOnRefreshListener {
                adapter.refresh()
            }
        }
    }


    override fun initViewModel(): WallteDetailViewModel = createViewModel()
    override fun initData() {
        lifecycleScope.launchWhenResumed {
            viewModel.pagingDataAuto {
                val ret = viewModel.server.zcjl(it, 1)
                PagingJsonResult(
                    list = ret.body()?.data?.record_list,
                    code = ret.body()?.code,
                    message = ret.body()?.message,
                    errorStr = ret.errorBody()?.string()
                )
            }.collect {
                adapter.submitData(it)
            }
        }
    }
}